<template>
  <dv-border-box-1 style="height:100%">
    <div id="border">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <!-- 待添加角色表单 -->
          <el-form
            v-if="!isDialog"
            :inline="true"
            width="100%"
            ref="roleaddForm"
            :rules="RulesAddRole"
            :model="pojoAddRole"
            class="demo-form-inline"
          >
            <el-form-item label="待添加角色" prop="rname">
              <el-input v-model="pojoAddRole.rname" placeholder="待添加角色名"></el-input>
            </el-form-item>
            <el-button type="primary" @click="addRole">确认添加</el-button>
            <el-button type="primary" @click="resetroleaddForm('roleaddForm')">置空</el-button>
            <el-button
              style="float:right"
              icon="el-icon-plus"
              type="primary"
              circle
              @click="handleAdd"
            ></el-button>
          </el-form>
          <!-- 搜索表单 -->
          <el-form
            ref="searchForm"
            :inline="true"
            width="100%"
            :model="searchMap"
            class="demo-form-inline"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="searchMap.name" placeholder="姓名"></el-input>
            </el-form-item>

            <el-form-item label="状态" prop="state">
              <el-select v-model="searchMap.state" clearable placeholder="请选择">
                <el-option
                  v-for="item in stateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tag }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="resetSearchForm('searchForm')"
              >置空</el-button>
            </el-form-item>
          </el-form>
          <!-- Table -->
          <el-table
            :data="list"
            style="width: 100%"
            highlight-current-row
            @current-change="clickCurrentChange"
          >
            <el-table-column sortable label="序号" type="index"></el-table-column>

            <el-table-column label="用户 ID" prop="id"></el-table-column>
            <el-table-column label="昵称" prop="username"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>

            <el-table-column v-if="!isDialog" label="最后一次登录" prop="lastlogin"></el-table-column>

            <el-table-column label="状态" prop="state">
              <template slot-scope="scope">
                <el-tag :type="scope.row.state === '1' ? '' : 'info'">
                  {{
                  scope.row.state === "1" ? "正常" : "异常"
                  }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              v-if="!isDialog"
              style="text-align:center;line-herght:100%;display:table-cell"
              label="操作"
              fixed="right"
              width="210px"
            >
              <template slot-scope="scope">
                <el-popover
                  style="background-color:black"
                  trigger="hover"
                  placement="left"
                  width="40px"
                >
                  <el-row :gutter="15">
                    <el-col :span="12">
                      <el-button
                        style="margin-left:0px;margin-top:2px"
                        size="mini"
                        type="primary"
                        round
                        @click="handleAddRole(scope.row.id)"
                      >分配角色</el-button>
                    </el-col>
                    <el-col :span="12">
                      <el-button
                        style="float:left"
                        size="mini"
                        type="danger"
                        round
                        @click="handleBlack(scope.row.id)"
                      >拉黑</el-button>
                    </el-col>
                  </el-row>
                  <el-button type="primary" size="mini" plain slot="reference">操作</el-button>
                </el-popover>

                <el-button
                  style="margin-left:5px"
                  type="warning"
                  size="mini"
                  plain
                  @click="handleEdit(scope.row.id)"
                >编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <div style="text-align:center">
      <el-button style="margin=0 auto" icon="el-icon-download" @click="loadMore">点击加载更多</el-button>
      <span style="float:right">共{{ total }}条记录</span>
    </div>
    <!-- 角色选择组件 -->
    <el-dialog title="addRole" :visible.sync="dialogRoleVisible" width="500px">
      <role-app @option-role="optionRole" :isRoleDialog="true"></role-app>
    </el-dialog>
    <!-- 添加用户组件 -->
    <!-- 抽屉 -->
    <el-drawer
      title="管理员编辑"
      size="50%"
      style="height:100%"
      :visible.sync="dialogUserEditVisible"
      :direction="direction"
    >
      <el-collapse v-model="activeName" style="height:100%" accordion>
        <el-collapse-item v-if="!isAdd" title="角色信息" name="roleList">
          <el-table
            highlight-current-row
            max-height="300"
            :data="
          RoleList.filter(
            data =>
              !search || data.rname.toLowerCase().includes(search.toLowerCase())
          )
        "
            style="width: 100%"
          >
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="角色编号" prop="rid"></el-table-column>
            <el-table-column label="角色名" prop="rname"></el-table-column>
            <el-table-column label="状态" prop="state">
              <template slot-scope="scope">
                <el-tag :type="scope.row.state === '1' ? '' : 'info'">
                  {{
                  scope.row.state=='1'?'使用中':'弃用'
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="right" width="250">
              <template slot="header" slot-scope="scope">
                <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
              </template>
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  plain
                  @click="handleDeleteRole(scope.row.rid)"
                >删除角色</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
        <el-collapse-item
          title="管理员信息"
          :style="isAdd?'overflow-y:auto;height:70%':'overflow-y:auto;height:60%'"
          name="userEdit"
        >
          <el-card class="box-card" shadow="hover">
            <el-form
              ref="pojoForm"
              class="demo-form-inline"
              :model="pojo"
              :rules="RulespojoForm"
              label-position="right"
              label-width="80px"
              size="mini"
            >
              <el-form-item v-if="!isAdd" label="编号" prop="id">
                <el-input readonly width="60px" v-model="pojo.id" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="用户名" prop="username">
                <el-input width="60px" v-model="pojo.username"></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="name">
                <el-input width="60px" v-model="pojo.name"></el-input>
              </el-form-item>
              <el-form-item v-if="!isAdd" label="最后一次登录" prop="lastlogin">
                <el-date-picker readonly v-model="pojo.lastlogin" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>

              <el-form-item v-if="!isAdd" label="状态" prop="state">
                <el-switch
                  v-model="pojo.state"
                  active-color="#13ce66"
                  inactive-color="grey"
                  active-value="1"
                  inactive-value="0"
                  @change="handleFormStateChange"
                ></el-switch>
              </el-form-item>
              <div style="float:right;margin-bottom:10px">
                <el-button @click="dialogUserEditVisible = false">取 消</el-button>

                <el-button
                  type="primary"
                  @click="pojo.id === null ? addAdmin() : updateAdmin('pojoForm')"
                >{{ this.pojo.id === null ? "添加" : "修改" }}</el-button>
              </div>
            </el-form>
          </el-card>
        </el-collapse-item>
      </el-collapse>
    </el-drawer>
     <!-- 角色选择组件 -->
    <el-dialog title="添加角色" :visible.sync="dialogRoleVisible" width="500px">
      <role-app @option-role="optionRole" :isRoleDialog="true"></role-app>
    </el-dialog>
  </dv-border-box-1>
</template>

<script>
import adminApi from "@/api/admin";
import roleApp from "@/views/user/role.vue";
import store from "../../store";
import { callbackify } from "util";
export default {
  components: {
    roleApp
  },
  props: {
    isDialog: Boolean
  },
  data() {
    return {
      isAdd: false, //是否为添加用户
      direction: "rtl",
      dialogUserEditVisible: false, //编辑用户窗口
      dialogRoleVisible: false, //添加角色窗口
      activeName: "",
      search: "",
      stateOptions: [
        {
          value: "1",
          label: "正常",
          tag: "OK"
        },
        {
          value: "0",
          label: "异常",
          tag: "black"
        },
        {
          value: "2",
          label: "全部",
          tag: "all"
        }
      ],

      //待添加角色信息
      pojoAddRole: {
        rid: "",
        rname: "",
        userid: ""
      },
      list: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      totalPage: 0, //总页数
      searchMap: {
        currentUserId: store.state.user.user.id,
        name: "",
        state: ""
      },
      pojo: {
        id: null,
        username: "",
        name:"",
        lastlogin: "",
        state: ""
      },
      RoleList: [], //用户的角色列表
      RulesAddRole: {
        rname: [
          { required: true, message: "待添加角色不能为空", trigger: "blur" }
        ]
      },
      RulespojoForm: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            min: 4,
            max: 15,
            message: "昵称长度在 4 到 15 个字符",
            trigger: "blur"
          }
        ],
        username: [{ required: true, message: "姓名不能为空", trigger: "blur" }]
      }
    };
  },
 
  mounted() {
    this.fetchData();
  },
  methods: {
   
    fetchData() {
      adminApi
        .searchPage(this.currentPage, this.pageSize, this.searchMap)
        .then(resp => {
          const respData = resp.data;
          if (respData.flag) {
            this.list = respData.data.rows;
            this.total = respData.data.total;
            this.totalPage =
              this.total / this.pageSize <= 1
                ? 1
                : Math.ceil(this.total / this.pageSize); //Math.ceil向上取整
            // console.log(this.list);
            //consoleconsole.log(this.totalPage)
          } else {
            this.$message({
              message: respData.message,
              type: "warning"
            });
          }
        });
    },
    /**
     * 打开添加用户窗口
     */
    handleAdd() {
      this.isAdd = true;
      this.dialogUserEditVisible = true;
      this.$nextTick(() => {
        this.$refs["pojoForm"].resetFields();
        this.checkPassword = "";
      });
      this.pojo.id = null;
    },
    /**
     * 添加管理员
     */
    addAdmin() {
      //console.log(this.$refs.pojoForm)
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          if (this.pojo.avatar !== "" && this.pojo.avatar !== null) {
            adminApi.addUser(this.pojo).then(resp => {
              if (resp.data.flag) {
                this.$message({
                  type: "success",
                  message: resp.data.message
                });
                this.dialogUserEditVisible = false;
                this.fetchData();
              } else {
                this.$message({
                  type: "warning",
                  message: resp.data.message
                });
              }
            });
          } else {
            this.$message({
              message: "请先上传头像",
              type: "warning"
            });
          }
        } else {
          this.$message({
            message: "请检查格式是否正确",
            type: "warning"
          });
        }
      });
    },
    /**
     * 打开编辑窗口
     */
    handleEdit(id) {
      this.handleAdd();
      this.isAdd = false;
      adminApi.getById(id).then(resp => {
        const respData = resp.data;
        if (respData.flag) {
          this.pojo = respData.data;
        } else {
          this.$message({
            type: "warning",
            message: respData.message
          });
        }
      });
      this.getRoleListById(id);
    },
    /**
     * 查询角色列表
     */
    getRoleListById(userid) {
      adminApi.getRoleListById(userid).then(respRole => {
        const respRoleData = respRole.data;
        if (respRoleData.flag) {
          this.RoleList = respRoleData.data;
        } else {
          this.$message({
            type: "warning",
            message: respRoleData.message
          });
        }
      });
    },
    /**
     * 根据管理员id删除角色
     */
    handleDeleteRole(rid) {
      this.$confirm("确定删除此角色吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          adminApi.deleteRoleById(this.pojo.id, rid).then(resp => {
            if (resp.data.flag) {
              this.$message({
                type: "success",
                message: resp.data.message
              });
              this.getRoleListById(this.pojo.id);
            }
          });
        })
        .catch(() => {
          return;
        });
    },
    /**
     * 修改管理员信息
     */
    updateAdmin() {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          adminApi.update(this.pojo).then(resp => {
            if (resp.data.flag) {
              this.$message({
                type: "success",
                message: resp.data.message
              });
              this.fetchData();
              this.dialogUserEditVisible = false;
            } else {
              this.$message({
                type: "warning",
                message: resp.data.message
              });
            }
          });
        } else {
          this.$message({
            type: "warning",
            message: "请检查填写的信息格式"
          });
        }
      });
    },
    handleFormStateChange(val){
            this.pojo.state=val
    },
    /**
     * 给管理员添加角色(打开窗口，赋值userid)
     */
    handleAddRole(id) {
      this.pojoAddRole.userid = id;
      this.dialogRoleVisible = true;
    },
    /**
     * 给管理员添加角色
     */
    addRole() {
      this.$refs.roleaddForm.validate(valid => {
        if (valid) {
          adminApi
            .addRoleForUser(this.pojoAddRole.userid, this.pojoAddRole.rid)
            .then(resp => {
              if (resp.data.flag) {
                this.$message({
                  type: "success",
                  message: resp.data.message
                });
                this.pojoAddRole = {};
              } else {
                this.$message({
                  type: "warning",
                  message: resp.data.message
                });
              }
            });
        }
      });
    },
    /**
     * 待添加用户置空
     */
    resetroleaddForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * 查询表单置空
     */
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * 拉黑
     */
    handleBlack(id) {
      this.$confirm("确定拉黑此用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          adminApi.blackUser(id).then(resp => {
            this.$message({
              type: resp.data.flag ? "success" : "error",
              message: resp.data.message
            });
            if (resp.data.flag) {
              this.fetchData();
            }
          });
        })
        .catch(() => {
          return;
        });
    },
  
   
    /**
     * 加载更多
     */
    loadMore() {
      if (this.currentPage < this.totalPage) {
        //没有到最后一页
        this.currentPage++;
        adminApi
          .searchPage(this.currentPage, this.pageSize, this.searchMap)
          .then(resp => {
            const respData = resp.data;
            if (respData.flag) {
              this.list = this.list.concat(respData.data.rows);
            } else {
              this.$message({
                message: respData.message,
                type: "warning"
              });
            }
          });
      } else {
        this.$message({
          type: "info",
          message: "已经全部加载完啦"
        });
      }
    },
    /**
     * 点击某行后触发该方法
     */
    clickCurrentChange(currentRow) {
      //点击后将数据传递到父组件（文章管理），触发父组件的option-category，父组件可以在option-category这个事件对应的处理函数中接收数据
      this.$emit("option-user", currentRow);
    },
    optionRole(currentRow) {
      if (currentRow.state === "0") {
        this.$message({
          type: "warning",
          message: "该角色已被弃用！"
        });
        return false;
      }
      this.pojoAddRole.rname = currentRow.rname; //角色名
      this.pojoAddRole.rid = currentRow.rid;
      this.dialogRoleVisible = false;
    },
   
   
  }
};
</script>
<style scoped>
#border {
  padding: 20px;
}
/*table  css */
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
  margin-right: 10px;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

</style>
